<template>
    <div class="science-login" id="h5index">
        <div class="science-center">
            <div class="science-data">
                <div class="fs-5">账号绑定</div>
                <div class="mb-3">绑定云课堂帐号，可以查询账号学习情况</div>
                <el-form ref="formref" :model="form" label-width="95px" size="default" :rules="rules" label-position="top">
                    <el-form-item class="text-item" label="云课堂的登录账号：" prop="phonenum">
                        <el-input placeholder="云课堂的登录账号" name="phonenum" v-model="form.phonenum"></el-input>
                    </el-form-item>
                    <el-form-item label="云课堂的登录密码：" class="text-item" prop="password">
                        <el-input placeholder="密码" name="password" type="password" v-model="form.password"></el-input>
                    </el-form-item>
                    <el-form-item label="您与云课堂账号的关系:" class="text-item" prop="_relationship">
                        <el-radio-group v-model="forget.relationship">
                            <el-radio label="家属" />
                            <el-radio label="老师" />
                            <el-radio label="本人" />
                            <el-radio label="其他" />
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="您的手机号：" class="text-item" prop="_phonenum">
                        <el-input placeholder="您的手机号：" v-model="forget.phonenum">
                            <template #append>
                                <button class="btn btn-login3" type="button" @click.stop.prevent="click2"
                                    :disabled="time2 !== 60" v-text="time2 == 60 ? '验证码' : time2"></button>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="短信验证码：" class="text-item" prop="_yzm">
                        <el-input placeholder="短信验证码" v-model="forget.yzm"></el-input>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12" class="col m-0 p-0">
                            <button class="btn d-block btn-login2" type="button" @click="login">登录</button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { useStore } from "vuex";
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import {
    asynccreatedzhimahuuer,
    asyncgetregistphoneVerificationCode,
    asyncgetzhimahuuer,
    asynclogin,
} from "../../api/index";
import { ElForm, ElMessage, FormInstance, FormRules } from "element-plus";
import { Storekey } from "../../interface";
import { useRouter } from "vue-router";
import { useStorage, useUrlSearchParams } from "@vueuse/core";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import { isPhonenum } from "../../util/RegExp";
const router = useRouter()
const users = useStorage<Studycodemodel.Iuser[]>('users', [])
const user = useStorage<Studycodemodel.Iuser>('user', {})
defineProps<{ icon: string }>()


const rules = reactive<FormRules>({
    password: [
        { required: true, message: '密码必须填写', trigger: 'blur' },
    ],
    phonenum: [
        { required: true, message: '账号必须填写', trigger: 'blur' },
    ],
    _phonenum: [
        { required: true, message: '手机号必须填写', trigger: 'blur' },
    ],
    _yzm: [
        { required: true, message: '验证码必须填写', trigger: 'blur' },
    ],
    _relationship: [
        { required: true, message: '关系请选择', trigger: 'blur' },
    ],
})

const url = new URL(window.location.href)
const params = url.searchParams
const unionid = params.get('unionid')
const openid = params.get('openid')
const form = reactive({
    password: "",
    phonenum: "",
    _phonenum: "",
    _yzm: "",
    _relationship: ''
})
const time2 = ref(60)

function getyzm() {

}

const formref = ref<FormInstance>()


const forget = reactive<{ phonenum: string, yzm: string, relationship: string }>({})

const store = useStore(Storekey)
async function click2() {
    const { phonenum } = forget;
    if (time2.value !== 60) return;
    if (isPhonenum.test(phonenum)) {
        await asyncgetregistphoneVerificationCode(phonenum);
        const x = setInterval(() => {
            time2.value = time2.value - 1;
            if (time2.value == 0) {
                clearInterval(x);
                time2.value = 60;
            }
        }, 1000);
    }
}
async function start() {
    if (unionid) {
        const e = await asyncgetzhimahuuer({ unionid })
        const { rows } = e
        users.value = rows.map(e => {
            return {
                ID: e.userid,
                password: e.user?.password,
                phonenum: e.user?.phonenum,
                name: e.user?.name
            }
        })
    }
}

async function login() {
    if (!openid && !unionid) {
        ElMessage.error('请使用微信登录')
        return
    }
    await formref.value?.validate((valid, fields) => {
        if (valid) {
            const { phonenum, password } = form;
            asynclogin({ ID: phonenum, password }).then((e) => {
                const u = users.value.findIndex(t => t.ID === e.ID)
                if (u !== -1) {
                    user.value = {
                        ID: e.ID,
                        name: e.name,
                        gid: e.gid,
                        password: password,
                        phonenum: e.phonenum
                    }
                    store.dispatch('actiononline')
                    router.push('/users')
                } else {
                    asynccreatedzhimahuuer({
                        userid: e.ID,
                        openid: openid,
                        unionid: unionid,
                        ...forget
                    }).then(() => {
                        start()
                        user.value = {
                            ID: e.ID,
                            name: e.name,
                            gid: e.gid,
                            password: password,
                            phonenum: e.phonenum
                        }
                        store.dispatch('actiononline')
                        router.push('/users')
                    }).catch(c => {
                        ElMessage.error(c);
                    })
                }
            }).catch(c => {
                ElMessage.error(c);
            })
        } else {
            console.log('error submit!', fields)
        }
    })

}


onMounted(() => {
    if (!openid) {
        ElMessage.error('请使用微信登录')
        return
    }
})

onUnmounted(() => {

})
watch(forget, e => {
    form._phonenum = e.phonenum
    form._yzm = e.yzm
    form._relationship = e.relationship
})

</script>



<style scoped>
.science-login {
    display: grid;
    height: calc(100vh - 89px);
    width: 100vw;
    align-content: center;
    position: relative;
    overflow: hidden;
    margin-top: -64px;
}

.science-center {
    height: 518px;
    background-repeat: no-repeat;
    background-size: contain;
    margin: 0 auto;
    border-radius: 8px;
    z-index: 1;
    display: flex;
}

.science-data {
    width: 442px;
    padding-left: 48px;
    padding-right: 74px;
    padding-top: 48px;
    background-image: url(https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/LOGO/zhimahulogo.png);
    background-repeat: no-repeat;
    background-position-x: center;
    background-position-y: top;
    background-size: 30%;
}

.science-data header {
    font-weight: 700;
    font-size: 36px;
    margin-bottom: 48px;
}



.btn-login2 {
    width: 148px;
    color: #fff;
    background: #17B44C;
    border-radius: 2px;
}

.btn-login3 {
    background: #17B44C;
    color: #fff;
}

.text-item {
    margin-bottom: 24px;
}
</style>

<style>
#h5index .el-input-group__append,
.el-input-group__prepend {
    padding: 0;
}
</style>